package com.example.administrator.demorecyclerview.auto_viewpager;

import android.content.Context;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by Administrator on 2018/1/30.
 */

@CoordinatorLayout.DefaultBehavior(MyAppBarLayout.FlingBehavior.class)
public class MyAppBarLayout extends AppBarLayout {
    public MyAppBarLayout(Context context) {
        super(context);
    }

    public MyAppBarLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public static final class FlingBehavior extends AppBarLayout.Behavior {
        private static final int TOP_CHILD_FLING_THRESHOLD = 3;
        private boolean isPositive;

        public FlingBehavior() {
        }

        public FlingBehavior(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        @Override
        public boolean onNestedFling(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, float velocityX, float velocityY, boolean consumed) {
            if (velocityY > 0 && !isPositive || velocityY < 0 && isPositive) {
                velocityY = velocityY * -1;
            }
            if (target instanceof RecyclerView && velocityY < 0) {
                final RecyclerView recyclerView = (RecyclerView) target;
                final View firstChild = recyclerView.getChildAt(0);
                final int childAdapterPosition = recyclerView.getChildAdapterPosition(firstChild);
                consumed = childAdapterPosition > TOP_CHILD_FLING_THRESHOLD;
            }
            return super.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed);
        }

        @Override
        public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed) {
            super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed);
            isPositive = dy > 0;
        }
    }
}
